﻿
using FileSecretAssemblyStandard;
using Ldt.DataEngin.PCPackage.Model;
using LdtJudge.DataEngine.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace Ldt.DataEngin.PCPackage
{
  public class FlowConfig
  {
    public string ConfigRootPath { get; set; }

    public string GetAnalysisFlow(string caseType,string docID,string appId = null,string courtId = null,string caseCause = null)
    {
      Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：请求参数caseType=" + caseType + "&docID=" + docID + "&appId=" + appId + "&courtId=" + courtId + "&caseCause=" + caseCause);
      WordParseConfigFileCommon configFileCommon = new WordParseConfigFileCommon(this.ConfigRootPath);
      GetConfigInfoModel getConfigInfoModel = new GetConfigInfoModel();
      Result result = new Result();
      Body body = new Body();
      List<ModuleConfig> moduleConfigList = new List<ModuleConfig>();
      if (string.IsNullOrEmpty(caseType) || string.IsNullOrEmpty(docID))
      {
        result.code = "1";
        result.message = "案件类型与文书ID是必填项，当前传入的参数caseType=" + caseType + ",docID=" + docID;
        getConfigInfoModel.result = result;
        getConfigInfoModel.body = (Body) null;
        string decode = JsonConvert.SerializeObject((object) getConfigInfoModel);
        Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：案件类型与文书ID是必填项,未填写完整！");
        return this.EnCodeBase64(65001, decode);
      }
      string str = configFileCommon.GeyProcessFileName(caseType, docID, appId, courtId, caseCause);
      string fileName = configFileCommon.GetFileName(str.ToLower());
      if (fileName != "notfound")
      {
        XmlNode rootNode = (XmlNode) null;
        ModuleConfig processFileInfo = configFileCommon.GetProcessFileInfo(fileName, ref rootNode);
        moduleConfigList.Add(processFileInfo);
        foreach (XmlNode childNode in rootNode.ChildNodes)
        {
          try
          {
            ModuleConfig moduleConfig = new ModuleConfig();
            ModuleConfig moduleConfigInfo = configFileCommon.GetModuleConfigInfo(childNode);
            moduleConfigList.Add(moduleConfigInfo);
          }
          catch (Exception ex)
          {
            Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：读取流程配置文件中发生异常" + ex.Message);
          }
        }
        result.code = "0";
        result.message = "成功";
        getConfigInfoModel.result = result;
        body.moduleConfig = moduleConfigList;
        getConfigInfoModel.body = body;
        Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：接口执行成功!" + Environment.NewLine);
      }
      else
      {
        result.code = "1";
        result.message = "失败，查找不到该符合条件的流程配置文件";
        getConfigInfoModel.result = result;
        getConfigInfoModel.body = (Body) null;
        Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：流程配置文件" + fileName + "不存在。" + Environment.NewLine);
      }
      return HttpHelp.EnDataBase64((object) JsonConvert.SerializeObject((object) getConfigInfoModel));
    }

    public string GetOptimizeCfgInfo(string caseType, string caseCause = null, string docType = null)
    {
      Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetOptimizeCfgInfo接口:传入参数 caseType=" + caseType + "caseCause=" + caseCause + " doctype=" + docType);
      GetConfigInfoModel getConfigInfoModel = new GetConfigInfoModel();
      getConfigInfoModel.result = new Result();
      Body body = new Body();
      List<ModuleConfig> moduleConfigList = new List<ModuleConfig>();
      string configRootPath = this.ConfigRootPath;
      string fileName1 = this.GetFileName(Path.Combine(this.ConfigRootPath, "config", "processConfig", "optimizeprocessconfig", caseType + ".xmlldt").ToLower());
      if (fileName1 != "notfound")
      {
        try
        {
          InterfaceFileSecret fileSecretInstance = FileSecretFactory.GetFileSecretInstance((FileSecretFactory.FileSecretType) 0);
          string content1 = fileSecretInstance.DecryptFileToContent(fileName1);
          XmlDocument xmlDocument1 = new XmlDocument();
          xmlDocument1.LoadXml(content1);
          XmlNode selectNode = xmlDocument1.SelectNodes("/root")[0];
          Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetOptimizeCfgInfo接口：开始加密流程配置文件内容，未加密前=" + selectNode.OuterXml);
          moduleConfigList.Add(new ModuleConfig()
          {
            number = "0",
            moduleName = "流程配置文件",
            filePath = fileName1.IndexOf("/config/") <= -1 ? fileName1.Substring(fileName1.IndexOf("\\config\\")).ToLower().Trim('\\') : fileName1.Substring(fileName1.IndexOf("/config/")).ToLower().Trim('\\'),
            executeCode = Path.GetFileName(fileName1),
            executeType = "file",
            code = "ProcessConfig",
            configContent = selectNode.OuterXml
          });
          foreach (XmlNode childNode in selectNode.ChildNodes)
          {
            string str1 = Path.Combine(configRootPath, childNode.Attributes["executefile"].Value.ToLower().Trim('\\'));
            string str2 = childNode.Attributes["zh_cn"].Value;
            ModuleConfig moduleConfig = new ModuleConfig();
            moduleConfig.number = childNode.Attributes["number"].Value;
            moduleConfig.moduleName = str2;
            moduleConfig.code = childNode.Attributes["code"].Value;
            moduleConfig.executeType = childNode.Attributes["executetype"].Value;
            moduleConfig.executeCode = childNode.Attributes["executecode"].Value;
            moduleConfig.filePath = childNode.Attributes["executefile"].Value.ToLower().Trim('\\');
            string fileFullName = str1.Replace("\\", "/");
            Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetOptimizeCfgInfo接口：读取流程配置文件中的'" + str2 + "'模块的配置文件" + fileFullName);
            if (moduleConfig.executeCode.ToLower() == "caseCauseElementCfg".ToLower())
              fileFullName = Path.Combine(configRootPath, moduleConfig.filePath, caseType + "_" + caseCause + ".xmlldt").Replace("\\", "/").ToLower();
            string fileName2 = this.GetFileName(fileFullName);
            Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetOptimizeCfgInfo接口：moduleConfigPath=" + fileName2);
            if (fileName2 != "notfound")
            {
              XmlDocument xmlDocument2 = new XmlDocument();
              try
              {
                string content2 = fileSecretInstance.DecryptFileToContent(fileName2);
                xmlDocument2.LoadXml(content2);
              }
              catch (Exception ex)
              {
                Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetOptimizeCfgInfo接口：load'" + str2 + "'模块的配置文件" + fileName2 + "错误!" + ex.Message);
              }
              XmlNodeList xmlNodeList = xmlDocument2.SelectNodes("/root");
              moduleConfig.mlflag = xmlNodeList[0].Attributes["mlflag"] != null ? xmlNodeList[0].Attributes["mlflag"].Value : "0";
              moduleConfig.configContent = xmlDocument2.OuterXml;
              Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetOptimizeCfgInfo接口：读取与加密'" + str2 + "'模块的配置文件" + fileName2 + "完成!");
            }
            else
            {
              moduleConfig.configContent = "";
              Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetOptimizeCfgInfo接口：" + str2 + "模块的配置文件" + fileName2 + "不存在!");
            }
            moduleConfigList.Add(moduleConfig);
          }
          getConfigInfoModel.result.code = "0";
          getConfigInfoModel.result.message = "成功";
          body.moduleConfig = moduleConfigList;
          getConfigInfoModel.body = body;
          Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetOptimizeCfgInfo接口：接口执行成功!" + Environment.NewLine);
        }
        catch (Exception ex)
        {
          Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetOptimizeCfgInfo接口：接口执行异常!" + Environment.NewLine + ex.Message + "----" + ex.StackTrace);
        }
      }
      else
      {
        getConfigInfoModel.result.code = "1";
        getConfigInfoModel.result.message = "文件不存在";
        getConfigInfoModel.body = (Body) null;
      }
      return this.EnCodeBase64(65001, JsonConvert.SerializeObject((object) getConfigInfoModel));
    }

    private string EnCodeBase64(int codepage, string decode)
    {
      string str;
      try
      {
        str = Convert.ToBase64String(Encoding.GetEncoding(codepage).GetBytes(decode));
      }
      catch
      {
        str = "";
      }
      return str;
    }

    private string GetFileName(string fileFullName)
    {
      string extension = Path.GetExtension(fileFullName);
      string withoutExtension = Path.GetFileNameWithoutExtension(fileFullName);
      string directoryName = Path.GetDirectoryName(fileFullName);
      string path = string.Empty;
      if (extension == ".xml")
        path = Path.Combine(directoryName, withoutExtension + ".xmlldt");
      if (extension == ".xmlldt")
        path = Path.Combine(directoryName, withoutExtension + ".xml");
      if (extension == ".json")
        path = Path.Combine(directoryName, withoutExtension + ".jsonldt");
      if (extension == ".jsonldt")
        path = Path.Combine(directoryName, withoutExtension + ".json");
      if (File.Exists(fileFullName))
        return fileFullName;
      if (File.Exists(path))
        return path;
      return "notfound";
    }
  }
}
